package com.jintian.smart.kernel.message.service;

import com.google.common.collect.Lists;
import com.jintian.smart.kernel.common.util.SmartBeanUtil;
import com.jintian.smart.kernel.core.domain.ResponseDTO;
import com.jintian.smart.kernel.core.enumeration.UserTypeEnum;
import com.jintian.smart.base.api.message.constant.MessageTemplateEnum;
import com.jintian.smart.base.api.message.entity.MessageEntity;
import com.jintian.smart.base.api.message.form.MessageQueryForm;
import com.jintian.smart.base.api.message.form.MessageSendForm;
import com.jintian.smart.base.api.message.form.MessageTemplateSendForm;
import com.jintian.smart.base.api.message.vo.MessageVO;
import com.jintian.smart.kernel.message.mapper.MessageMapper;
import com.jintian.smart.kernel.orm.impl.AbstractEntityServiceImpl;
import org.apache.commons.text.StringSubstitutor;
import org.beetl.sql.core.page.PageResult;
import org.beetl.sql.core.query.LambdaQuery;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MessageService extends AbstractEntityServiceImpl<MessageMapper, MessageEntity> {
    /**
     * 分页查询 消息
     */
    public PageResult<MessageVO> query(MessageQueryForm queryForm) {
        //        LambdaQuery<MessageEntity> query = messageMapper.createLambdaQuery();
//        if (queryForm.getReceiverUserType() != null) {
//            query.andEq(MessageEntity::getReceiverUserType, queryForm.getReceiverUserType());
//        }
//        if (queryForm.getReceiverUserId() != null) {
//            query.andEq(MessageEntity::getReceiverUserId, queryForm.getReceiverUserId());
//        }
//        if (queryForm.getMessageType() != null) {
//            query.andEq(MessageEntity::getMessageType, queryForm.getMessageType());
//        }
//        if (StringUtil.isNotEmpty(queryForm.getSearchWord())) {
//            query.andLike(MessageEntity::getTitle, "%" + queryForm.getSearchWord() + "%");
//            query.andLike(MessageEntity::getContent, "%" + queryForm.getSearchWord() + "%");
//        }
//        if (queryForm.getReadFlag() != null) {
//            query.andEq(MessageEntity::getReadFlag, queryForm.getReadFlag());
//        }
//        if (queryForm.getReceiverUserId() != null) {
//            query.andEq(MessageEntity::getReceiverUserId, queryForm.getReceiverUserId());
//        }
//        if (queryForm.getStartDate() != null) {
//            query.andGreatEq(MessageEntity::getCreateTime, queryForm.getStartDate());
//        }
//        if (queryForm.getEndDate() != null) {
//            query.andGreatEq(MessageEntity::getCreateTime, queryForm.getEndDate());
//        }
//
//        PageResult<MessageEntity> pageResult = query.page(queryForm.getPageNo(), queryForm.getPageSize());
//        return SmartBeanUtil.copyPage(pageResult, MessageVO.class);

        return this.getEntityMapper().query(queryForm);
    }

    /**
     * 查询未读消息数量
     */
    public Long getUnreadCount(UserTypeEnum userType, Long userId) {
        return this.getUnreadCount(userType.getValue(), userId);
    }

    /**
     * 更新已读状态
     */
    public void updateReadFlag(Long messageId, UserTypeEnum userType, Long receiverUserId) {
        this.updateReadFlag(messageId, userType.getValue(), receiverUserId, 1);
    }


    /**
     * 发送【模板消息】
     */
    public void sendTemplateMessage(MessageTemplateSendForm... sendTemplateForms) {
        List<MessageSendForm> sendFormList = Lists.newArrayList();
        for (MessageTemplateSendForm sendTemplateForm : sendTemplateForms) {
            MessageTemplateEnum msgTemplateTypeEnum = sendTemplateForm.getMessageTemplateEnum();
            StringSubstitutor stringSubstitutor = new StringSubstitutor(sendTemplateForm.getContentParam());
            String content = stringSubstitutor.replace(msgTemplateTypeEnum.getContent());

            MessageSendForm messageSendForm = new MessageSendForm();
            messageSendForm.setMessageType(msgTemplateTypeEnum.getMessageTypeEnum().getValue());
            messageSendForm.setReceiverUserType(sendTemplateForm.getReceiverUserType().getValue());
            messageSendForm.setReceiverUserId(sendTemplateForm.getReceiverUserId());
            messageSendForm.setTitle(msgTemplateTypeEnum.getDesc());
            messageSendForm.setContent(content);
            messageSendForm.setDataId(sendTemplateForm.getDataId());
            sendFormList.add(messageSendForm);
        }
        this.sendMessage(sendFormList);
    }

    /**
     * 发送消息
     */
    public void sendMessage(MessageSendForm... sendForms) {
        this.sendMessage(Lists.newArrayList(sendForms));
    }

    /**
     * 批量发送通知消息
     */
    public void sendMessage(List<MessageSendForm> sendList) {
        for (MessageSendForm sendDTO : sendList) {
            String verify = SmartBeanUtil.verify(sendDTO);
            if (null != verify) {
                throw new RuntimeException("send msg error: " + verify);
            }
        }
        List<MessageEntity> messageEntityList = sendList.stream().map(e -> {
            MessageEntity messageEntity = new MessageEntity();
            messageEntity.setMessageType(e.getMessageType());
            messageEntity.setReceiverUserType(e.getReceiverUserType());
            messageEntity.setReceiverUserId(e.getReceiverUserId());
            messageEntity.setDataId(String.valueOf(e.getDataId()));
            messageEntity.setTitle(e.getTitle());
            messageEntity.setContent(e.getContent());
            return messageEntity;
        }).collect(Collectors.toList());
        this.saveBatch(messageEntityList);
    }

    // 删除消息
    public ResponseDTO<String> delete(Long messageId) {
        if (messageId == null) {
            return ResponseDTO.userErrorParam();
        }
        this.deleteById(messageId);
        return ResponseDTO.ok();
    }

    /**
     * 更新已读状态
     */
    public int updateReadFlag(Long messageId, Integer receiverUserType, Long receiverUserId, Integer readFlag) {
        LambdaQuery<MessageEntity> query = this.getEntityMapper().createLambdaQuery().set(MessageEntity::getReadFlag, readFlag).set(MessageEntity::getReadTime, new Date())
                .andEq(MessageEntity::getMessageId, messageId)
                .andEq(MessageEntity::getReceiverUserType, receiverUserType)
                .andEq(MessageEntity::getReceiverUserId, receiverUserId);
        return query.update();
    }

    /**
     * 查询未读消息数
     */
    public Long getUnreadCount(Integer receiverUserType, Long receiverUserId) {
        LambdaQuery<MessageEntity> query = this.getEntityMapper().createLambdaQuery()
                .andEq(MessageEntity::getReceiverUserType, receiverUserType)
                .andEq(MessageEntity::getReceiverUserId, receiverUserId)
                .andEq(MessageEntity::getReadFlag, 0);
        return query.count();
    }
}